package cn.ghf.pet.controller;

import cn.ghf.basic.util.AjaxResult;
import cn.ghf.basic.util.LoginContext;
import cn.ghf.basic.util.PageList;
import cn.ghf.pet.domain.Pet;
import cn.ghf.pet.query.PetQuery;
import cn.ghf.pet.service.IPetService;
import cn.ghf.user.domain.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/pet")
public class PetController {

    @Autowired
    private IPetService petService;

    /**
     * 分页查询
     * @param query
     * @return
     */
    @PostMapping
    private PageList<Pet> getPets(@RequestBody PetQuery query){
        System.out.println(query.getKeywords());
        PageList<Pet> pets = petService.getPets(query);
        return pets;
    }

    /**
     * 上架
     * @param ids
     * @return
     */
    @PostMapping("/onsale")
    public AjaxResult onSale(@RequestBody List<Long> ids){
        try {
            petService.onSale(ids);
            return AjaxResult.createAjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.createAjaxResult().setMsg("系统错误");
        }
    }

    /**
     * 下架
     * @param ids
     * @return
     */
    @PostMapping("/offsale")
    public AjaxResult offSale(@RequestBody List<Long> ids){
        try {
            petService.offSale(ids);
            return AjaxResult.createAjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.createAjaxResult().setMsg("系统错误");
        }
    }

    /**
     * 获取宠物信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Pet getById(@PathVariable("id") Long id){
        return petService.loadById(id);
    }

    /**
     * 领养
     * @param id
     * @return
     */
    @GetMapping("/adopt/{id}")
    public AjaxResult adopt(@PathVariable("id") Long id, HttpServletRequest request){
        try {
            LoginInfo loginInfo = LoginContext.getLogin(request);
            petService.adopt(id,loginInfo.getId());
            return AjaxResult.createAjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.createAjaxResult().setMsg("系统异常");
        }


    }
}
